<?php
if(!interface_exists('XExceptionHandler', false)){
	require(dirname(__FILE__).DIRECTORY_SEPARATOR.'XExceptionHandler.php');
}
class XBasicExceptionHandler implements XExceptionHandler{
	public function handle(Exception $e){
		if(is_null($e)){
			return false;
		}
		//log first
		XEventContext::singleton()->publish(new XLoggingEvent($this, ERROR, $e->getMessage(), $e));
		//load user handler
		$handler = XAnnotation::singleton(get_class($e))
			->get('Exception.handler');
		if(class_exists($handler, false)){
			$handler = new $handler();
			if($handler instanceof XExceptionHandler){
				return $handler->handle($e);
			}
		}
		//redirect if defined in config	
		$redirection = XConfig::singleton()->get("project.exception.{$e->getCode()}.redirect");
		if(is_string($redirection)){
			XServletResponse::singleton()->redirect($redirection);
		}
		//load default 404/500 html
		$file = dirname(__FILE__)."/page/{$e->getCode()}.default";
		if(file_exists($file)){
			echo file_get_contents($file);
			return true;
		}
		//load user exception html
		//load default exception html
		foreach(array(
			PROJECT_ROOT.'/config/error',
			dirname(__FILE__).'/page',
			) as $dir){
			if($this->_html($e, $dir)){
				return true;
			}
		}
		return false;
	}
	
	private function _html($e, $dir){
		$file = $dir.'/exception.default';	
		$traceFile = $dir.'/trace.default';	
		if(!file_exists($file) || !file_exists($traceFile)){
			return false;
		}
		$html = file_get_contents($file);
		$html = str_replace("%{class}", get_class($e), $html);
		$html = str_replace("%{code}", $e->getCode(), $html);
		$html = str_replace("%{message}", $e->getMessage(), $html);
		$html = str_replace("%{file}", $e->getFile(), $html);
		$html = str_replace("%{line}", $e->getLine(), $html);
		$traces = $e->getTrace();		
		$traceTemplate = file_get_contents($traceFile);
		$traceHtml = '';
		foreach($traces as $index => $trace){
			$str = $traceTemplate;
			$str = str_replace("%{index}", $index, $str);
			foreach($trace as $key => $value){
				if(!is_array($value)){					
					$str = str_replace("%{{$key}}", $value, $str);
				}
			}
			$traceHtml .= $str;
		}
		$html = str_replace("%{trace}", $traceHtml, $html);
		echo $html;
		return true;		
	}
}
?>